from flask import Flask, request
import time
import hmac
import hashlib
import base64
import urllib
from secret_config import SECRET
import os

def gen_sign(timestamp):
    secret = SECRET
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode("utf-8")
    return sign

app = Flask(__name__)

BASE_DIR = '/home/cxl/projects'
def deploy(dir_name):
    dir_path = os.path.join(BASE_DIR, dir_name)
    if not os.path.exists(dir_path):
        return "no such dir"
    cmd = " && ".join([
        f'cd "{dir_path}"',
        f'git clean -f',
        f'sh deploy.sh',
    ])
    print(cmd)
    os.system(cmd)
    return "ok"

@app.route("/<dir_name>", methods=['POST'])
def index(dir_name):
    sign = request.args.get('sign')
    ts = request.args.get('timestamp')
    if sign != gen_sign(ts):
        return "sign error"
    if abs(time.time() - int(ts)/1000) > 60*20: #20min
        return "timestamp error"
    return deploy(dir_name)

if __name__ == '__main__':
    app.run('0.0.0.0', port=7788)
